<template>
  <nav class="navbar">
    <div class="nav-left-placeholder"></div>
    <div class="nav-links">
      <router-link
        v-for="item in navItems"
        :key="item.path"
        :to="item.path"
        class="nav-link"
        :class="{ active: $route.path === item.path }"
      >
        {{ item.title }}
        <!-- 消息红点 -->
        <span
          v-if="item.path === '/chat' && showUnreadDot"
          class="unread-dot"
        ></span>
      </router-link>
      <div class="active-underline"></div>
    </div>
    <div class="user-info" @click="toggleDropdown">
      <span class="nickname">{{ nickname }}</span>
      <img :src="avatarPath" alt="Avatar" class="avatar" />
      <!-- 头像旁的通知红点 -->
      <span
        v-if="unreadInformCount > 0"
        class="notification-badge"
      >
        {{ unreadInformCount > 99 ? '99+' : unreadInformCount }}
      </span>
      <!-- 下拉菜单 -->
      <div v-show="showDropdown" class="dropdown-menu" @click.stop>
        <div class="dropdown-item" @click="goToNotifications">
          通知
          <span v-if="unreadInformCount > 0" class="notification-badge-dropdown">
            {{ unreadInformCount > 99 ? '99+' : unreadInformCount }}
          </span>
        </div>
        <div class="dropdown-item" @click="goToProfile">个人信息</div>
        <div class="dropdown-item" @click="logout">登出</div>
      </div>
    </div>
  </nav>
</template>

<script>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import apiClient from '@/utils/api' // 引入api实例'

export default {
  setup () {
    const userInfo = ref(null)
    const nickname = ref('')
    const avatarPath = ref('')
    const route = useRoute()
    const router = useRouter()
    const showDropdown = ref(false)
    const showUnreadDot = ref(false) // 未读消息红点状态
    const unreadInformCount = ref(0) // 未读通知数
    let websocketMessageHandler = null // WebSocket消息处理器引用

    // 从 localStorage 获取用户信息
    onMounted(async () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        userInfo.value = JSON.parse(userInfoStr)
        nickname.value = userInfo.value.nickname
        avatarPath.value = userInfo.value.avatarPath

        // 检查未读消息状态
        checkUnreadMessages()
        // 检查未读通知
        checkUnreadInform()

        // 设置WebSocket监听
        setupWebsocketListener()
      }

      // 初始加载时更新下划线位置
      await nextTick()
      updateUnderlinePosition()

      // 添加全局点击事件监听器
      document.addEventListener('click', handleClickOutside)

      // 页面关闭前移除监听器
      window.addEventListener('beforeunload', async () => {
        await removeWebsocketListener()
        document.removeEventListener('click', handleClickOutside)
      })
    })

    // 根据 userType 动态生成导航项
    const navItems = computed(() => {
      if (!userInfo.value) return []
      if (userInfo.value.userType === 'candidate') {
        return [
          { title: '首页', path: '/home' },
          { title: '职位', path: '/jobList' },
          { title: '消息', path: '/chat' },
          { title: '社区', path: '/community' }
        ]
      } else if (userInfo.value.userType === 'employer') {
        return [
          { title: '首页', path: '/home' },
          { title: '管理', path: '/employerJobList' },
          { title: '消息', path: '/chat' },
          { title: '社区', path: '/community' }
        ]
      }
      return []
    })

    // 监听路由变化，更新下划线位置
    watch(() => route.path, async () => {
      await nextTick()
      updateUnderlinePosition()

      // 当进入聊天页面时，隐藏红点并标记消息为已读
      if (route.path === '/chat') {
        clearUnreadDot()
      }
    })

    // 清除未读红点
    const clearUnreadDot = async () => {
      try {
        // 先设置本地状态为false
        showUnreadDot.value = false

        // 调用API标记所有消息为已读
        const response = await apiClient.put('/chat/clearUnreadMessage')

        // 检查API响应
        if (response.data.code !== '200') {
          console.error('清除未读消息失败:', response.data.message)
          // 如果API调用失败，仍然尝试重新检查状态
          await checkUnreadMessages()
        }
      } catch (error) {
        console.error('清除未读消息状态失败:', error)
        // 如果网络请求失败，仍然尝试重新检查状态
        await checkUnreadMessages()
      }
    }

    // 检查未读消息
    const checkUnreadMessages = async () => {
      try {
        const response = await apiClient.get('/chat/getUnreadMessage')
        if (response.data.code === '200') {
          showUnreadDot.value = response.data.data
        } else {
          console.error('获取未读消息失败:', response.data.message)
          showUnreadDot.value = false // 如果获取失败，默认不显示红点
        }
      } catch (error) {
        console.error('检查未读消息失败:', error)
        showUnreadDot.value = false // 如果网络请求失败，默认不显示红点
      }
    }

    // 检查未读通知
    const checkUnreadInform = async () => {
      try {
        const response = await apiClient.get('/chat/getUnreadInform')
        if (response.data.code === '200') {
          unreadInformCount.value = response.data.data
        } else {
          console.error('获取未读通知失败:', response.data.message)
          unreadInformCount.value = 0
        }
      } catch (error) {
        console.error('检查未读通知失败:', error)
        unreadInformCount.value = 0
      }
    }

    // 清除未读通知
    const clearUnreadInform = async () => {
      try {
        // 调用API标记所有通知为已读
        const response = await apiClient.put('/chat/updateInformStatus')

        if (response.data.code === '200') {
          unreadInformCount.value = 0
        } else {
          console.error('清除未读通知失败:', response.data.message)
        }
      } catch (error) {
        console.error('清除未读通知失败:', error)
      }
    }

    // 跳转到通知列表
    const goToNotifications = async () => {
      await clearUnreadInform()
      router.push('/inform')
    }

    // 设置WebSocket监听器
    const setupWebsocketListener = async () => {
      try {
        const { useWebsocketStore } = await import('@/store/websocket')
        const websocketStore = useWebsocketStore()

        // 修改 setupWebsocketListener 中的消息处理函数
        websocketMessageHandler = (data) => {
          // 判断是否为系统消息
          const isSystemMessage = data.isSystem || data.type === 'system' || data.messageType === 'system'

          // 只有在非聊天页面时才处理消息红点显示
          if (route.path !== '/chat') {
            // 如果是聊天消息，显示红点
            if (!isSystemMessage && data.type === 'chat') {
              showUnreadDot.value = true
            }
            // 如果是系统消息（用户上线/下线），不处理红点显示
          }

          // 处理通知消息
          if (data.isSystem === true && data.type === 'inform') {
            unreadInformCount.value = Math.min(unreadInformCount.value + 1, 99)
          }
        }

        // 添加消息监听器
        websocketStore.addMessageListener(websocketMessageHandler)
      } catch (error) {
        console.error('设置WebSocket监听器失败:', error)
      }
    }

    // 移除WebSocket监听器
    const removeWebsocketListener = async () => {
      if (websocketMessageHandler) {
        try {
          const { useWebsocketStore } = await import('@/store/websocket')
          const websocketStore = useWebsocketStore()
          websocketStore.removeMessageListener(websocketMessageHandler)
        } catch (error) {
          console.error('移除WebSocket监听器失败:', error)
        }
      }
    }

    // 更新下划线位置
    const updateUnderlinePosition = () => {
      const activeIndex = navItems.value.findIndex(item => route.path === item.path)
      const activeUnderline = document.querySelector('.active-underline')

      if (activeIndex !== -1 && activeUnderline) {
        const activeLink = document.querySelectorAll('.nav-link')[activeIndex]
        if (activeLink) {
          activeUnderline.style.width = `${activeLink.offsetWidth}px`
          activeUnderline.style.left = `${activeLink.offsetLeft}px`
        }
      }
    }

    // 切换下拉菜单显示状态
    const toggleDropdown = () => {
      showDropdown.value = !showDropdown.value
    }

    // 跳转到个人信息页面
    const goToProfile = () => {
      // 根据用户类型跳转到不同的个人信息页面
      router.push('/user/profile')
      showDropdown.value = false
    }

    // 登出功能
    const logout = async () => {
      try {
        // 发送登出请求
        await apiClient.post('/user/logout')
      } catch (error) {
        // 即使请求失败也执行登出操作
        console.error('Logout request failed:', error)
      } finally {
        // 移除WebSocket监听器
        await removeWebsocketListener()

        // 断开WebSocket连接
        try {
          const { useWebsocketStore } = await import('@/store/websocket')
          const websocketStore = useWebsocketStore()
          websocketStore.resetConnection() // 重置连接状态
        } catch (error) {
          console.error('Failed to disconnect WebSocket:', error)
        }

        // 清除用户信息和token
        localStorage.removeItem('userInfo')
        localStorage.removeItem('token')
        // 跳转到登录页面
        router.push('/')
        showDropdown.value = false
      }
    }

    // 点击其他地方关闭下拉菜单
    const handleClickOutside = (event) => {
      if (showDropdown.value && !event.target.closest('.user-info')) {
        showDropdown.value = false
      }
    }

    return {
      navItems,
      nickname,
      avatarPath,
      showDropdown,
      showUnreadDot, // 返回红点状态
      unreadInformCount, // 返回未读通知数
      toggleDropdown,
      goToProfile,
      logout,
      goToNotifications // 返回跳转到通知列表的方法
    }
  }
}
</script>

<style scoped>
.notification-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  font-weight: bold;
  min-width: 18px;
  height: 18px;
  line-height: 14px;
  text-align: center;
}

.notification-badge-dropdown {
  background-color: #ff4d4f;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  font-weight: bold;
  min-width: 18px;
  height: 18px;
  line-height: 14px;
  text-align: center;
  margin-left: 8px;
  display: inline-block;
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  padding: 10px 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
  position: relative;
  z-index: 100;
}

.nav-left-placeholder {
  width: 120px;
}

.nav-links {
  display: flex;
  gap: 50px;
  justify-content: center;
  flex: 1;
  position: relative;
}

.nav-link {
  color: #1890ff;
  text-decoration: none;
  font-size: 16px;
  white-space: nowrap;
  padding: 5px 0;
  position: relative;
  z-index: 1;
}

.nav-link:hover {
  text-decoration: underline;
}

.nav-link.active {
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 120px;
  justify-content: flex-end;
  cursor: pointer;
  position: relative;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.active-underline {
  position: absolute;
  bottom: 0;
  height: 2px;
  background-color: #1890ff;
  transition: all 0.3s ease;
  border-radius: 2px;
}

.unread-dot {
  position: absolute;
  top: 0;
  right: -6px;
  width: 8px;
  height: 8px;
  background-color: #ff4d4f;
  border-radius: 50%;
  border: 2px solid #ffffff;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  width: 120px;
  z-index: 1000;
  margin-top: 8px;
}

.dropdown-menu::before {
  content: '';
  position: absolute;
  top: -6px;
  right: 14px;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-bottom: 6px solid #ffffff;
}

.dropdown-item {
  padding: 10px 16px;
  font-size: 14px;
  color: #333333;
  cursor: pointer;
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.dropdown-item:first-child {
  border-radius: 4px 4px 0 0;
}

.dropdown-item:last-child {
  border-radius: 0 0 4px 4px;
}
</style>
